﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ARR.Entities.Common;
using ARR.Entities.ComponentModel;
using System.Reflection;
using ARR.Shared;

namespace ARR.Entities.Validation.Common
{
    [Serializable]
    public class Required : ValidationBase
    {
        public Required(string propertyName, string displayName = null) : base(propertyName, null)
        {
            string fieldName = displayName == null ? propertyName : displayName;
            base.ErrorMessage = string.Format(Errors.RequiredValidation, fieldName);
        }

        public override bool Validate(ValidatableEntity entity)
        {
            PropertyInfo pi = entity.GetType().GetProperty(this.PropertyName);
            if (pi == null)
                throw new Exception(string.Format("The Property '{0}' is not a valid property name", this.PropertyName));
            object value = pi.GetValue(entity, null);
                                    
            if (value is String)
            {
                return !string.IsNullOrWhiteSpace(value.ToString());
            }
            
            return value != null;
        }
    }
}
